<?php

//require_once ('FTAWebServices/FTACurlPost.php');

	
	set_include_path(get_include_path() . ":/usr/local/gravitate/Zend/ZendFramework-1.10.2-minimal/library/");
//	require_once("fta.php");
	fta_registerModules(
		array(
			'FTAWebServices/FTACurlPost',
//			'FTAWebServices/FTAGeoIp',
			'Zend/Cache/Manager'
		)
	);
	
	
	

define("FTA_GEOIP_HOST",'http://geoip3.maxmind.com');
define("FTA_GEOIP_PORT",'80');
define("FTA_GEOIP_ENDPOINT",'/a');

class FTAGeoIp  {
	
    // Hold an instance of the class
    private static $instance;

    private $curlClient;
    private $cache;
    private $cacheConfig;
    private $geoIpKey;
    
    //query url http://geoip3.maxmind.com/a?l=RtsVtMDG0Cp1&i=202.191.38.58
    
    // A private constructor; prevents direct creation of object
    private function __construct() {
    	global $FTAGeoIpKey;
    	if (is_null($FTAGeoIpKey)){
    		throw new FTAException("No GeoIp Key Configured");
    	}
    	$this->geoIpKey = $FTAGeoIpKey;
    	
    	global $FTAGeoIpCacheConfig;
    	if (is_null($FTAGeoIpCacheConfig)){
    		throw new FTAException("Cache Configured");
    	}
    	$this->cacheConfig = $FTAGeoIpCacheConfig;
    }


    
    function getCountryForIP($ip, $useCache=true){
    	
    	$country = null;  
    	$key = 'ip_'.strtr($ip,'.','_');
    	if ($useCache){
    		if (is_null($this->cache)){
    			
				$this->cache = Zend_Cache::factory(
					'Core',//Always Core
					$this->cacheConfig['backEnd']['name'],
					$this->cacheConfig['frontEnd']['options'],
					$this->cacheConfig['backEnd']['options']
				);
				
                                 			
    		}
    		//get from the cache    
    		$country = $this->cache->load($key);		
    	}
    	
    	if (false === $country || is_null($country)){
    		
    		$u = FTA_GEOIP_HOST . ":" . FTA_GEOIP_PORT . FTA_GEOIP_ENDPOINT . "?l=" . $this->geoIpKey . "&i=" . $ip;
    		$country = @file_get_contents( $u );
    		
    		//'(null),IP_NOT_FOUND';
    		//error .. if error persist null??? nope.. 
    		if (0 === strpos($country,'(null)')){
    			$country = "--";	
    		}

    		if ($useCache && !is_null($country) && $country !== false){
    			$this->cache->save($country, $key);	
    		}
    	}
    	
    	if ('--' == $country || false === $country || is_null($country))
    		return null;
    		
    	return $country;
    }
    
    
    function flushCache(){
    	if (!is_null($this->cache)){
    		$this->cache->clean(Zend_Cache::CLEANING_MODE_ALL);
    	}
    }
    
    /**
     * Singleton method
     * @return FTAGeoIp
     */
    public static function singleton() {
        if (!isset(self::$instance)) {
            //$c = get_called_class();
            self::$instance = new static();
        }

        return self::$instance;
    }
    
	/**
	 * 
	 * Clone method override so that we can't create multiple instances
	 * @throws FTAException
	 */    
    public function __clone(){
    	throw new FTAException("Cannot clone Singleton");
    }

}


function fta_getClientIp() {
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                
            	//if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                //   return $ip;
                //}
                
            	//if we have an ip address ... return the first one we get.. 
            	
            	if( preg_match('/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/', trim($ip))){
            		return $ip;
            	}
            }
        }
    }
    return null;
}
